package com.idlecode.panel;

import cn.hutool.core.util.StrUtil;
import com.idlecode.bean.DataSourceEntity;
import com.idlecode.config.GenDataSource;
import com.idlecode.manage.CodeFormatManage;
import com.idlecode.manage.DataSourceFormManage;
import com.idlecode.service.CodeFormatService;
import com.idlecode.service.DataSourceService;
import com.intellij.openapi.ui.Messages;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.table.JBTable;
import com.intellij.util.ui.WrapLayout;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.sql.SQLException;
import java.util.List;

/**
 * @program: IdleCode
 * @description
 * @author: rongjuwei
 * @create: 2024-02-05 17:06
 **/
public class DataSourcesPanel extends JPanel {
    // 创建表格模型
    private DefaultTableModel tableModel;
    private JTable table;

    public DataSourcesPanel() {
        //按钮
        JPanel topJPanel = new JPanel(new WrapLayout(WrapLayout.CENTER));
        //调整
        topJPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 500));
        JButton testBtn = new JButton("测试");
        // 创建 RGB 颜色对象
        Color color = new Color(255, 102, 102);
        // 设置按钮字体颜色
        testBtn.setForeground(color);
        // 测试按钮点击事件的监听器
        testBtn.addActionListener(e -> testDataSource());

        JButton addBtn = new JButton("新增");
        // 添加按钮点击事件的监听器
        addBtn.addActionListener(e -> addDataSource());

        JButton deleteBtn = new JButton("删除");
        deleteBtn.addActionListener(e -> deleteDataSource());

        JButton editBtn = new JButton("编辑");
        editBtn.addActionListener(e -> editDataSource());

        JButton queryBtn = new JButton("查询");
        queryBtn.addActionListener(e -> queryBtnAction());

        JButton codeFormat = new JButton("代码格式");
        codeFormat.addActionListener(e -> codeFormatBtnAction());

        topJPanel.add(testBtn);
        topJPanel.add(addBtn);
        topJPanel.add(deleteBtn);
        topJPanel.add(editBtn);
        topJPanel.add(queryBtn);
        topJPanel.add(codeFormat);
        //列表显示
        JPanel bottomJPanel = new JPanel(new BorderLayout());
        tableModel = new DefaultTableModel();

        // 添加列名
        tableModel.addColumn("连接名");
        tableModel.addColumn("数据源类型");
        tableModel.addColumn("数据源URL");
        //tableModel.addColumn("用户名");

        List<DataSourceEntity> dataSourcesRows = DataSourceService.getInstance().getDataSources();
        for (DataSourceEntity dataSourcesRow : dataSourcesRows) {
            // 添加数据行
            tableModel.addRow(new Object[]{dataSourcesRow.getConnName(), dataSourcesRow.getDbType(), dataSourcesRow.getConnUrl()});
        }

        // 创建表格
        table = new JBTable(tableModel);
        // 设置 JTable 的自动调整列宽度模式为 AUTO_RESIZE_SUBSEQUENT_COLUMNS
        // 这样可以确保在调整列宽度时，只调整之后的列宽度，而不会影响之前的列
        table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
        // 获取表头
        JTableHeader header = table.getTableHeader();

        // 设置表头字段居中
        setHeaderAlignment(header, SwingConstants.CENTER);
        // 将表格放置在滚动窗格中
        JScrollPane scrollPane = new JBScrollPane(table);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        bottomJPanel.add(scrollPane);
        // 垂直排列
        setLayout(new BorderLayout());
        add(topJPanel, BorderLayout.NORTH);
        add(bottomJPanel, BorderLayout.CENTER);
        addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                int jpWidth = getWidth();
                table.setPreferredScrollableViewportSize(new Dimension(jpWidth, table.getPreferredScrollableViewportSize().height));
                // 设置列宽度比例
                setColumnProportionalWidth(table, 0, 0.25, jpWidth);
                setColumnProportionalWidth(table, 1, 0.15, jpWidth);
                setColumnProportionalWidth(table, 2, 0.6, jpWidth);
            }
        });
    }

    private void addDataSource() {
        DataSourceFormManage dataSourceFormManage = new DataSourceFormManage(this);
        dataSourceFormManage.show();
    }

    private void editDataSource() {
        int selectedRow = table.getSelectedRow();
        if (selectedRow != -1) { // 判断是否有选中的行
            List<DataSourceEntity> dataSources = DataSourceService.getInstance().getDataSources();
            DataSourceEntity dataSourceEntity = dataSources.get(selectedRow);
            DataSourceFormManage dataSourceFormManage = new DataSourceFormManage(
                    selectedRow,
                    dataSourceEntity,
                    this);
            dataSourceFormManage.show();
        } else {
            Messages.showMessageDialog("请先选中数据源再点击编辑按钮！", "提示", Messages.getWarningIcon());
        }
    }

    private void deleteDataSource() {
        int selectedRow = table.getSelectedRow();
        if (selectedRow != -1) { // 判断是否有选中的行
            List<DataSourceEntity> dataSources = DataSourceService.getInstance().getDataSources();
            DataSourceEntity dataSourceEntity = dataSources.get(selectedRow);
            //删除数据库代码格式配置
            CodeFormatService.getInstance().deleteCodeFormatEntity(dataSourceEntity.getDsId());
            dataSources.remove(selectedRow);
            // 删除选中的行
            tableModel.removeRow(selectedRow);
        } else {
            Messages.showMessageDialog("请先选中数据源再点击删除按钮！", "提示", Messages.getWarningIcon());
        }
    }

    private void testDataSource() {
        int selectedRow = table.getSelectedRow();
        if (selectedRow != -1) { // 判断是否有选中的行
            List<DataSourceEntity> dataSources = DataSourceService.getInstance().getDataSources();
            DataSourceEntity dataSourceEntity = dataSources.get(selectedRow);
            GenDataSource genDataSource = null;
            try {
                genDataSource = new GenDataSource(dataSourceEntity);
                if (genDataSource.getConnection() == null) {
                    Messages.showMessageDialog("连接失败，网络异常！", "提示", Messages.getInformationIcon());
                } else {
                    Messages.showMessageDialog("连接成功！", "提示", Messages.getInformationIcon());
                }
            } catch (Exception exception) {
                Messages.showMessageDialog(StrUtil.format("连接失败！{}", exception.getMessage()), "异常", Messages.getErrorIcon());
            } finally {
                try {
                    if (genDataSource.getConnection() != null) {
                        genDataSource.getConnection().close();
                    }
                } catch (SQLException ex) {
                    Messages.showMessageDialog("连接关闭失败！", "异常", Messages.getErrorIcon());
                }
            }
        } else {
            Messages.showMessageDialog("请先选中数据源再点击测试按钮！", "提示", Messages.getWarningIcon());
        }
    }

    private static void setColumnProportionalWidth(JTable table, int columnIndex, double proportion, int jpWidth) {
        TableColumn column = table.getColumnModel().getColumn(columnIndex);
        int width = (int) (proportion * jpWidth);
        column.setPreferredWidth(width);
    }

    private static void setHeaderAlignment(JTableHeader header, int alignment) {
        for (int i = 0; i < header.getColumnModel().getColumnCount(); i++) {
            TableColumn column = header.getColumnModel().getColumn(i);
            column.setHeaderRenderer(new HeaderRenderer(alignment));
        }
    }

    // 清除表格模型中的数据
    private static void clearData(DefaultTableModel model) {
        int rowCount = model.getRowCount();
        for (int i = rowCount - 1; i >= 0; i--) {
            model.removeRow(i);
        }
    }

    public void queryBtnAction() {
        clearData(tableModel);
        List<DataSourceEntity> dataSourcesRows = DataSourceService.getInstance().getDataSources();
        for (DataSourceEntity dataSourcesRow : dataSourcesRows) {
            // 添加数据行
            tableModel.addRow(new Object[]{dataSourcesRow.getConnName(), dataSourcesRow.getDbType(), dataSourcesRow.getConnUrl()});
            // 调整 JTable 的首选大小
            table.setPreferredScrollableViewportSize(table.getPreferredSize());

            // 通知父容器重新布局
            table.revalidate();
        }
    }

    public void codeFormatBtnAction() {
        int selectedRow = table.getSelectedRow();
        if (selectedRow != -1) { // 判断是否有选中的行
            List<DataSourceEntity> dataSources = DataSourceService.getInstance().getDataSources();
            DataSourceEntity dataSourceEntity = dataSources.get(selectedRow);
            GenDataSource genDataSource = null;
            try {
                genDataSource = new GenDataSource(dataSourceEntity);
                if (genDataSource.getConnection() == null) {
                    Messages.showMessageDialog("数据源连接失败，网络异常！", "提示", Messages.getInformationIcon());
                } else {
                    new CodeFormatManage(genDataSource).show();
                }
            } catch (Exception exception) {
                Messages.showMessageDialog(StrUtil.format("连接失败！{}", exception.getMessage()), "异常", Messages.getErrorIcon());
            } finally {
                try {
                    if (genDataSource.getConnection() != null) {
                        genDataSource.getConnection().close();
                    }
                } catch (SQLException ex) {
                    Messages.showMessageDialog("连接关闭失败！", "异常", Messages.getErrorIcon());
                }
            }
        } else {
            Messages.showMessageDialog("请先选中数据源再点击代码格式按钮！", "提示", Messages.getWarningIcon());
        }
    }

    static class HeaderRenderer extends DefaultTableCellRenderer {
        HeaderRenderer(int alignment) {
            setHorizontalAlignment(alignment);
        }
    }
}
